<!--
 * @Author: DT1604\ZPL zhoupeili@dpc.com.cn
 * @Date: 2022-05-28 09:48:37
 * @LastEditors: DT1604\ZPL zhoupeili@dpc.com.cn
 * @LastEditTime: 2022-06-23 17:20:31
 * @FilePath: \energy-om-platform\src\views\cabint\log.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="cmds">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select
          v-model="form.equipmentType"
          placeholder="请选择设备类型"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in enums['EQUIPMENT_TYPE']"
            :key="index"
            :label="item.label"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        <el-input v-model="form.version" placeholder="请输入版本号"></el-input>
      </el-form-item>
      <el-form-item label="MD5校验码" prop="md5">
        <el-input v-model="form.md5" placeholder="请输入MD5校验码"></el-input>
      </el-form-item>
      <div class="tips">
        <el-link type="danger" :underline="false"
          >注：若填写此项，则会根据所填内容创建目录；否则默认根目录
          <br />可以用'/' 不能用'\',如：www/datas
        </el-link>
      </div>
      <el-form-item label="FTP目录">
        <el-input
          v-model="ftpath"
          placeholder="请输入FTP目录"
          @keyup.native="keyUp"
          @keydown.native="keydown"
          :disabled="fileList.length > 0"
        ></el-input>
      </el-form-item>
      <el-form-item label="上传文件" prop="fileUrl">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          multiple
          :limit="1"
          :http-request="uploadRequest"
          :on-change="handleChange"
          :on-exceed="esceedUpload"
          :on-remove="removeFile"
          :file-list="fileList"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>
      <el-form-item class="dialog-footer">
        <el-button @click="resetForm('form')">取消</el-button>
        <el-button
          type="primary"
          @click="submitForm('form')"
          :loading="btnLoading"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { equip, softversion, software } from "@/api/cabint";
import { mapGetters } from "vuex";

export default {
  props: {
    updateDialogVisible: {
      default: true,
      type: Boolean,
    },
    // 设备类型
    equipType: {
      type: String,
      default: "",
    },
    currentRow: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      form: {
        equipmentType: "", //类型
        version: "", //版本号
        md5: "", //MD5校验码
        fileUrl: "",
        filename: "",
      },
      ftpath:'',//文件目录
      rules: {
        equipmentType: [
          { required: true, message: "请选择类型", trigger: "change" },
        ],
        version: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        md5: [{ required: true, message: "请输入md5", trigger: "blur" }],
      },
      btnLoading: false, //按钮loading
      formData: null, //上传模板数据
      fileList: [], //文件列表
    };
  },
  watch: {
    updateDialogVisible: {
      handler(newVal, oldVal) {
        if (!newVal) {
          this.resetData();
        }
      },
      immediate: true,
    },
    equipType: {
      handler(newVal, oldVal) {},
      immediate: true,
    },
    currentRow: {
      handler(newVal, oldVal) {
        if (newVal.id) {
          //编辑
          let { id, equipmentType, version, md5, fileUrl, filename } = {
            ...newVal,
          };
          this.form = { id, equipmentType, version, md5, fileUrl, filename };

          this.fileList = [{ url: fileUrl, name: filename }];
          this.ftpath = fileUrl;
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(["enums"]),
  },

  methods: {
    //限制输入特殊字符
    keyUp(e) {
      e.target.value = e.target.value.replace(
        /[`~!@#$%^&*()_\-+=<>?:"{}|,.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
        ""
      );
      this.ftpath = e.target.value;
    },
    // 只能输入汉字、英文、数字
    keydown(e) {
      e.target.value = e.target.value.replace(
        /[^\a-\z\A-\Z0-9\u4E00-\u9FA5/]/g,
        ""
      );
      this.ftpath = e.target.value;
    },
    esceedUpload(file) {
      this.$message.warning("只能上传一个文件!");
    },
    uploadRequest(file) {
      //自定义上传
      this.formData = new FormData();
      this.formData.append("file", file.file);
      this.formData.append("path", this.ftpath);
     
      software("/upload", "post", this.formData, 1).then((res) => {
        let datas = res.data;
        this.form.filename = datas.filename;
        this.form.fileUrl = datas.filepath;
      });
    },

    resetData() {
      this.resetForm("form");
      this.form = {
        equipmentType: "",
        version: "",
        md5: "",
        fileUrl: "",
        filename: "",
      };
      this.ftpath = "";
      this.fileList = [];
      this.btnLoading = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isDoAdd();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.emitClose();
    },
    // 通知关闭弹框
    emitClose() {
      this.$emit("closeDialog");
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    removeFile(file,fileList){
      this.fileList = [];
    },

    async doAdd() {
      this.btnLoading = true;
      let url = this.currentRow.id ? "/update" : "/insert";
      let method = this.currentRow.id ? "put" : "post";
      await software(url, method, this.form, 2)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.emitClose();
            this.$emit("resetData");
          }
        })
        .finally((complete) => {
          this.btnLoading = false;
        });
    },
    isDoAdd() {
      let msg = this.currentRow.id ? "编辑" : "新增";
      this.$confirm(`是否确认要${msg}吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.doAdd();
      });
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
  margin-top: 100px;
}
.tips {
  margin: 30px 17% 10px;
}
</style>
